//高阶函数-函数作为参数
function forEach(arr, fn) {
  for (let i = 0; i < arr.length; i++) {
    fn(arr[i]);
  }
}

//测试
let arr1 = [1, 3, 4, 7, 8];
forEach(arr1, function (item) {
  console.log(item);
});

//filter
function filter(arr, fn) {
  let results = [];
  for (let i = 0; i < arr.length; i++) {
    if (fn(arr[i])) {
      results.push(arr[i]);
    }
  }
  return results;
}

//测试
let arr2 = [1, 3, 4, 7, 8];
let a = filter(arr2, function (item) {
  return item % 2 === 0;
});
console.log(a);

//高阶函数-函数作为返回值
function makeFn() {
  let msg = "hello function";
  return function () {
    console.log(msg);
  };
}
// let fn = makeFn();
// fn();
// makeFn()();

//once
function once(fn) {
  let done = false;
  return function () {
    if (!done) {
      done = true;
      return fn.apply(null, arguments);
    }
  };
}

let pay = once(function (money) {
  console.log(`支付：$ ${money}`);
});
pay(5);
pay(5);
pay(5);
pay(5);
pay(5);

//模拟常用高阶函数：map、every、some
//map
const map = (arr, fn) => {
  let results = [];
  for (let value of arr) {
    results.push(fn(value));
  }
  return results;
};
//测试
let arr3 = [1, 2, 3, 4];
arr3 = map(arr3, (v) => v * v);
console.log(arr3);

//every
const every = (arr, fn) => {
  let result = true;
  for (let value of arr) {
    result = fn(value);
    if (!result) {
      break;
    }
  }
  return result;
};
//测试
let arr4 = [11, 12, 14];
let arr5 = [1, 12, 11];
let e = every(arr5, (v) => v > 10);
console.log(e);

//some
const some = (arr, fn) => {
  let result = false;
  for (let value of arr) {
    result = fn(value);
    if (result) {
      break;
    }
  }
  return result;
};
//测试
let arr6 = [1, 3, 4, 5, 7];
let s = some(arr6, (v) => v % 2 === 0);
console.log(s);
